﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Xml.Linq;
namespace NoteBox
{
    public enum ListViewSE {InBox, OutBox}

    public delegate void dResp(string str);
    public delegate void dTable(Message _message);

    public class mButton : Button
    {
        private int id;
        public int ID
        {
            get
            {
                return id;
            }
        }

        public mButton(string _name, int _id, int _top, int _left)
        {
            id = _id;
            //
            Name = _name;
            Text = _name;
            AutoSize = true;
            BackColor = Color.Black;
            FlatStyle = FlatStyle.Flat;
            ForeColor = Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            Top = _top;
            Left = _left;
            UseVisualStyleBackColor = false;
            Parent = Form1.formMail;
            Click += new EventHandler(mButton_Click);
        }

        void mButton_Click(object sender, EventArgs e)
        {
            SetActive();
        }

        public void SetActive()
        {
            foreach (mButton mb in MailForm.mailButtons)
                mb.SetPassive();
            MailForm.mails[id].Visible = true;
            BackColor = Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(50)))), ((int)(((byte)(90)))));
            Form1.TaskChanged = true;
            MailForm.activeMail = id;
        }

        public void SetPassive()
        {
            MailForm.mails[id].Visible = false;
            BackColor = Color.Black;
            SendToBack();
        }
    }

    public class mMail : Panel
    {
        // у нас есть имя. логин... т.п.
        public string mMailName;
        public string mLogin;
        public string mPassword;
        public string mServer;
        public int mPort;
        public bool mSsl;
        public bool mAutoLoad;
        public int mAutoLoadTime;
        //   показывает - сейчас отображены входящие или исходящие.
        private ListViewSE showingListView = ListViewSE.InBox;
        public ListViewSE ShowingListView
        {
            get { return showingListView; }
        }
        //
        #region Оглашение кнопочек...
        private System.Windows.Forms.ListView listView1;
        private System.Windows.Forms.ColumnHeader columnID;
        private System.Windows.Forms.ColumnHeader columnFrom;
        private System.Windows.Forms.ColumnHeader columnSubject;
        private System.Windows.Forms.ColumnHeader columnDate;
        private System.Windows.Forms.ColumnHeader columnFile;
        private System.Windows.Forms.Label labelStop;
        private System.Windows.Forms.Button zbutlist;
        private System.Windows.Forms.Button zbutpanel;
        private System.Windows.Forms.Label labelAll;
        private System.Windows.Forms.Label labelDownload;
        //
        private System.Windows.Forms.Label labelStarInBox;
        private System.Windows.Forms.Button buttonInBox;
        private System.Windows.Forms.Button buttonOutBox;
        private System.Windows.Forms.Label labelStarOutBox;
        private System.Windows.Forms.TextBox textBoxSearch;
        private System.Windows.Forms.Label labelSearch;
        private System.Windows.Forms.Label labelShowCount;
        private System.Windows.Forms.Label labelMenu;
        //
        Button buttonHeaderDate;
        Button buttonHeaderID;
        Button buttonHeaderFrom;
        Button buttonHeaderSubject;
        #endregion
        // конструктор
        public mMail(string _mailname, string _login, string _pass, string _server, int _port,
            bool _ssl, bool _autoload, int _autoloadtime)
        {
            mMailName = _mailname;
            mLogin = _login;
            mPassword = _pass;
            mServer = _server;
            mPort = _port;
            mSsl = _ssl;
            mAutoLoad = _autoload;
            mAutoLoadTime = _autoloadtime;
            //
            #region кнопочки и прочие компоненты
            this.listView1 = new System.Windows.Forms.ListView();
            this.columnID = new System.Windows.Forms.ColumnHeader();
            this.columnFrom = new System.Windows.Forms.ColumnHeader();
            this.columnSubject = new System.Windows.Forms.ColumnHeader();
            this.columnDate = new System.Windows.Forms.ColumnHeader();
            this.columnFile = new System.Windows.Forms.ColumnHeader();
            buttonHeaderID = new Button();
            buttonHeaderFrom = new Button();
            buttonHeaderSubject = new Button();
            buttonHeaderDate = new Button();
            this.labelAll = new System.Windows.Forms.Label();
            this.zbutlist = new System.Windows.Forms.Button();
            this.zbutpanel = new System.Windows.Forms.Button();
            labelStop = new Label();
            //
            this.labelMenu = new System.Windows.Forms.Label();
            this.labelShowCount = new System.Windows.Forms.Label();
            this.labelSearch = new System.Windows.Forms.Label();
            this.textBoxSearch = new System.Windows.Forms.TextBox();
            this.labelStarOutBox = new System.Windows.Forms.Label();
            this.labelStarInBox = new System.Windows.Forms.Label();
            this.buttonInBox = new System.Windows.Forms.Button();
            this.buttonOutBox = new System.Windows.Forms.Button();
            //
            // 
            // listView1
            // 
            this.listView1.Activation = System.Windows.Forms.ItemActivation.OneClick;
            //this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            //            | System.Windows.Forms.AnchorStyles.Left)
            //            | System.Windows.Forms.AnchorStyles.Right)));
            this.listView1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(8)))), ((int)(((byte)(28)))), ((int)(((byte)(61)))));
            this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnID,
            this.columnFrom,
            this.columnSubject,
            this.columnFile,
            this.columnDate});
            this.listView1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.listView1.FullRowSelect = true;
            this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            this.listView1.LabelEdit = true;
            this.listView1.Location = new System.Drawing.Point(32, 36);
            this.listView1.Name = "listView1";
            this.listView1.TabIndex = 3;
            this.listView1.TileSize = new System.Drawing.Size(1, 1);
            this.listView1.UseCompatibleStateImageBehavior = false;
            this.listView1.View = System.Windows.Forms.View.Details;
            //this.listView1.HotTracking = true;
            // 
            // columnID
            // 
            this.columnID.Text = "№";
            this.columnID.Width = 30;
            // 
            // columnFrom
            // 
            this.columnFrom.Text = "Отправитель";
            this.columnFrom.Width = 100;
            // 
            // columnSubject
            // 
            this.columnSubject.Text = "Тема";
            this.columnSubject.Width = 300;
            // 
            // columnDate
            // 
            this.columnDate.Text = "дата";
            this.columnDate.Width = 130;
            // 
            // columnFile
            // 
            this.columnFile.Text = "";
            this.columnFile.Width = 0;
            ///
            // 
            // labelMenu
            // 
            this.labelMenu.AutoSize = true;
            this.labelMenu.Cursor = System.Windows.Forms.Cursors.Hand;
            this.labelMenu.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.labelMenu.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.labelMenu.Name = "labelMenu";
            this.labelMenu.Size = new System.Drawing.Size(89, 13);
            this.labelMenu.TabIndex = 39;
            this.labelMenu.Text = "Меню действий.";
            // 
            // labelShowCount
            // 
            this.labelShowCount.AutoSize = true;
            this.labelShowCount.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.labelShowCount.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.labelShowCount.Name = "labelShowCount";
            this.labelShowCount.Size = new System.Drawing.Size(234, 13);
            this.labelShowCount.TabIndex = 38;
            this.labelShowCount.Text = "Входящие. Всего: 0.";
            // 
            // labelSearch
            // 
            this.labelSearch.AutoSize = true;
            this.labelSearch.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.labelSearch.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.labelSearch.Name = "labelSearch";
            this.labelSearch.Size = new System.Drawing.Size(42, 13);
            this.labelSearch.TabIndex = 37;
            this.labelSearch.Text = "Поиск:";
            // 
            // textBoxSearch
            // 
            this.textBoxSearch.BackColor = System.Drawing.Color.Black;
            this.textBoxSearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.textBoxSearch.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.textBoxSearch.Name = "textBoxSearch";
            this.textBoxSearch.Size = new System.Drawing.Size(100, 20);
            this.textBoxSearch.TabIndex = 36;
            textBoxSearch.KeyUp+=new KeyEventHandler(textBoxSearch_KeyUp);
            // 
            // labelStarOutBox
            // 
            this.labelStarOutBox.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.labelStarOutBox.ForeColor = System.Drawing.Color.Purple;
            this.labelStarOutBox.Location = new System.Drawing.Point(14, 108);
            this.labelStarOutBox.Name = "labelStarOutBox";
            this.labelStarOutBox.Size = new System.Drawing.Size(13, 9);
            this.labelStarOutBox.TabIndex = 35;
            this.labelStarOutBox.Text = "*";
            this.labelStarOutBox.Visible = false;
            // 
            // labelStarInBox
            // 
            this.labelStarInBox.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.labelStarInBox.ForeColor = System.Drawing.Color.Purple;
            this.labelStarInBox.Location = new System.Drawing.Point(14, 36);
            this.labelStarInBox.Name = "labelStarInBox";
            this.labelStarInBox.Size = new System.Drawing.Size(9, 9);
            this.labelStarInBox.TabIndex = 32;
            this.labelStarInBox.Text = "*";
            this.labelStarInBox.Visible = false;
            // 
            // buttonInBox
            // 
            this.buttonInBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(50)))), ((int)(((byte)(90)))));
            this.buttonInBox.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonInBox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonInBox.Image = global::NoteBox.Properties.Resources.Rec;
            this.buttonInBox.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.buttonInBox.Location = new System.Drawing.Point(11, 35);
            this.buttonInBox.Name = "buttonInBox";
            this.buttonInBox.Size = new System.Drawing.Size(21, 72);
            this.buttonInBox.TabIndex = 34;
            this.buttonInBox.UseVisualStyleBackColor = false;
            buttonInBox.Click += new EventHandler(buttonInBox_Click);
            // 
            // buttonOutBox
            // 
            this.buttonOutBox.BackColor = System.Drawing.Color.Black;
            this.buttonOutBox.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonOutBox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonOutBox.Image = global::NoteBox.Properties.Resources.Sent;
            this.buttonOutBox.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.buttonOutBox.Location = new System.Drawing.Point(11, 106);
            this.buttonOutBox.Name = "buttonOutBox";
            this.buttonOutBox.Size = new System.Drawing.Size(21, 96);
            this.buttonOutBox.TabIndex = 33;
            this.buttonOutBox.UseVisualStyleBackColor = false;
            buttonOutBox.Click += new EventHandler(buttonOutBox_Click);
            ///
            // 
            // buttonHeaderDate
            // 
            this.buttonHeaderDate.BackColor = System.Drawing.Color.Black;
            this.buttonHeaderDate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonHeaderDate.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonHeaderDate.Location = new System.Drawing.Point(468, 14);
            this.buttonHeaderDate.Name = "buttonHeaderDate";
            this.buttonHeaderDate.Size = new System.Drawing.Size(127, 22);
            this.buttonHeaderDate.TabIndex = 29;
            this.buttonHeaderDate.Text = "Дата сообщения";
            this.buttonHeaderDate.UseVisualStyleBackColor = false;
            this.buttonHeaderDate.MouseMove += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseMove);
            this.buttonHeaderDate.MouseDown += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseDown);
            this.buttonHeaderDate.MouseUp += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseUp);
            
            // 
            // buttonHeaderSubject
            // 
            this.buttonHeaderSubject.BackColor = System.Drawing.Color.Black;
            this.buttonHeaderSubject.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonHeaderSubject.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonHeaderSubject.Location = new System.Drawing.Point(188, 14);
            this.buttonHeaderSubject.Name = "buttonHeaderSubject";
            this.buttonHeaderSubject.Size = new System.Drawing.Size(274, 22);
            this.buttonHeaderSubject.TabIndex = 28;
            this.buttonHeaderSubject.Text = "Тема";
            this.buttonHeaderSubject.UseVisualStyleBackColor = false;
            this.buttonHeaderSubject.MouseMove += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseMove);
            this.buttonHeaderSubject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseDown);
            this.buttonHeaderSubject.MouseUp += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseUp);
            // 
            // buttonHeaderFrom
            // 
            this.buttonHeaderFrom.BackColor = System.Drawing.Color.Black;
            this.buttonHeaderFrom.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonHeaderFrom.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonHeaderFrom.Location = new System.Drawing.Point(63, 14);
            this.buttonHeaderFrom.Name = "buttonHeaderFrom";
            this.buttonHeaderFrom.Size = new System.Drawing.Size(126, 22);
            this.buttonHeaderFrom.TabIndex = 27;
            this.buttonHeaderFrom.Text = "Отправитель";
            this.buttonHeaderFrom.UseVisualStyleBackColor = false;
            this.buttonHeaderFrom.MouseMove += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseMove);
            this.buttonHeaderFrom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseDown);
            this.buttonHeaderFrom.MouseUp += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseUp);
            // 
            // buttonHeaderID
            // 
            this.buttonHeaderID.BackColor = System.Drawing.Color.Black;
            this.buttonHeaderID.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.buttonHeaderID.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.buttonHeaderID.Location = new System.Drawing.Point(31, 14);
            this.buttonHeaderID.Name = "buttonHeaderID";
            this.buttonHeaderID.Size = new System.Drawing.Size(35, 22);
            this.buttonHeaderID.TabIndex = 26;
            this.buttonHeaderID.Text = "№";
            this.buttonHeaderID.UseVisualStyleBackColor = false;
            this.buttonHeaderID.MouseMove += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseMove);
            this.buttonHeaderID.MouseDown += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseDown);
            this.buttonHeaderID.MouseUp += new System.Windows.Forms.MouseEventHandler(this.buttonHeader_MouseUp);
            // 
            // labelAll
            // 
            this.labelAll.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.labelAll.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.labelAll.Name = "labelAll";
            this.labelAll.Size = new System.Drawing.Size(400, 15);
            this.labelAll.TabIndex = 25;
            this.labelAll.Text = " ";
            // 
            // zbutlist
            // 
            //this.zbutlist.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            //            | System.Windows.Forms.AnchorStyles.Left)
            //            | System.Windows.Forms.AnchorStyles.Right)));
            this.zbutlist.BackColor = System.Drawing.Color.Black;
            this.zbutlist.Enabled = false;
            this.zbutlist.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.zbutlist.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.zbutlist.Location = new System.Drawing.Point(31, 35);
            this.zbutlist.Name = "zbutlist";
            this.zbutlist.Size = new System.Drawing.Size(574, 292);
            this.zbutlist.TabIndex = 23;
            this.zbutlist.Text = "first mail";
            this.zbutlist.UseVisualStyleBackColor = false;
            // 
            // zbutpanel
            // 
            //this.zbutpanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            //            | System.Windows.Forms.AnchorStyles.Left)
            //            | System.Windows.Forms.AnchorStyles.Right)));
            this.zbutpanel.BackColor = System.Drawing.Color.Black;
            this.zbutpanel.Enabled = false;
            this.zbutpanel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.zbutpanel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.zbutpanel.Location = new System.Drawing.Point(0, 0);
            this.zbutpanel.Name = "zbutpanel";
            this.zbutpanel.Size = new System.Drawing.Size(608, 376);
            this.zbutpanel.TabIndex = 24;
            this.zbutpanel.Text = "first mail";
            this.zbutpanel.UseVisualStyleBackColor = false;
            // 
            // labelStop
            // 
            //this.labelStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.labelStop.AutoSize = true;
            this.labelStop.Cursor = System.Windows.Forms.Cursors.Hand;
            this.labelStop.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.labelStop.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(113)))), ((int)(((byte)(130)))), ((int)(((byte)(160)))));
            this.labelStop.Name = "labelStop";
            this.labelStop.Size = new System.Drawing.Size(74, 13);
            this.labelStop.TabIndex = 30;
            this.labelStop.Text = "проверить ящик";
            labelStop.Click += new EventHandler(labelStop_Click);
            //
            //
            // Mail
            // 
            this.Controls.Add(this.labelDownload);
            this.Controls.Add(this.labelAll);
            this.Controls.Add(this.listView1);
            this.Controls.Add(this.labelStop);
            this.Controls.Add(this.zbutlist);
            this.Controls.Add(this.zbutpanel);
            this.Controls.Add(this.buttonHeaderDate);
            this.Controls.Add(this.buttonHeaderID);
            this.Controls.Add(this.buttonHeaderSubject);
            this.Controls.Add(this.buttonHeaderFrom);
            this.Controls.Add(this.labelMenu);
            this.Controls.Add(this.labelShowCount);
            this.Controls.Add(this.labelSearch);
            this.Controls.Add(this.textBoxSearch);
            this.Controls.Add(this.labelStarOutBox);
            this.Controls.Add(this.labelStarInBox);
            this.Controls.Add(this.buttonInBox);
            this.Controls.Add(this.buttonOutBox);
            //
            this.Visible = false;
            this.Location = new System.Drawing.Point(12, 33);
            this.Name = "panel1";
            this.TabIndex = 8;
            #endregion
            // РАЗМЕРЫ И ЛОКАЦИИ ЭЛЕМЕНТОВ
            this.listView1.Size = new System.Drawing.Size(560, 290);
            this.zbutlist.Size = new System.Drawing.Size(562, 292);
            this.Size = new System.Drawing.Size(608, 376);
            this.zbutpanel.Size = new System.Drawing.Size(608, 376);
            //
            this.textBoxSearch.Location = new System.Drawing.Point(392, 338);
            this.labelSearch.Location = new System.Drawing.Point(344, 341);
            this.labelStop.Location = new System.Drawing.Point(506, 359);
            this.labelMenu.Location = new System.Drawing.Point(506, 341);
            this.labelShowCount.Location = new System.Drawing.Point(28, 341);
            this.labelAll.Location = new System.Drawing.Point(28, 359);
            //
            this.listView1.MaximumSize =
                new Size(Screen.PrimaryScreen.WorkingArea.Width-100, Screen.PrimaryScreen.WorkingArea.Height);
            ColumnSizeChange(this);
            HeightSizeChange();
            this.buttonHeaderID.BringToFront();
            this.buttonHeaderFrom.BringToFront();
            this.buttonHeaderSubject.BringToFront();
            this.buttonHeaderDate.BringToFront();
            
            this.labelStop.BringToFront();
            this.labelMenu.BringToFront();
            this.labelSearch.BringToFront();
            this.labelShowCount.BringToFront();
            this.buttonOutBox.BringToFront();
            this.buttonInBox.BringToFront();
            this.textBoxSearch.BringToFront();
            
        }

        

        #region изменение размеров - mouseмувы разные + изменение высоты + ширины колонок
        bool formMoved = false;
        int XPos = 0;
        private void buttonHeader_MouseDown(object sender, MouseEventArgs e)
        {
            if (sender is Button)
            {
                if (e.X < ((Button)sender).Width - 5)
                    return;
                XPos = e.X;
                formMoved = true;
            }
        }
        private void buttonHeader_MouseMove(object sender, MouseEventArgs e)
        {
            if (sender is Button)
            {
                if (e.X > ((Button)sender).Width - 5)
                    Cursor.Current = Cursors.VSplit;
                else
                    Cursor.Current = Cursors.Default;
            }
            if (formMoved)
            {
                if (sender is Button)
                {
                    if (e.X < 30)
                        return;
                    ((Button)sender).Width = e.X;
                    Parent.Width = Width + 24;
                    ColumnSizeChange(this);
                }
            }
        }
        private void buttonHeader_MouseUp(object sender, MouseEventArgs e)
        {
            if (formMoved)
            {
                formMoved = false;
                foreach (mMail ml in MailForm.mails)
                {
                    ColumnSizeChange(ml);
                }
            }
        }
        /// <summary>
        /// В данном случае, если мы изменяем только эту форму( MouseMove ), то передаем this.
        /// Тогда получаем стандартное изменение. Если передаем обьект - другой, то получаем приведение к виду
        /// "видимой формы"
        /// </summary>
        /// <param name="obj">Обьект, который мы передаем</param>
        void ColumnSizeChange(mMail obj)
        {
            obj.buttonHeaderID.Left = buttonHeaderID.Left;
            if (obj.buttonHeaderID.Width > listView1.MaximumSize.Height * 0.12)
                obj.buttonHeaderID.Width = (int)(listView1.MaximumSize.Height * 0.12);
            obj.columnID.Width = buttonHeaderID.Width;
            obj.buttonHeaderFrom.Left = buttonHeaderID.Left + buttonHeaderID.Width;
            if (obj.buttonHeaderFrom.Width > listView1.MaximumSize.Height * 0.4)
                obj.buttonHeaderFrom.Width = (int)(listView1.MaximumSize.Height * 0.4);
            obj.columnFrom.Width = buttonHeaderFrom.Width;
            obj.buttonHeaderSubject.Left = buttonHeaderFrom.Left + buttonHeaderFrom.Width;
            if (obj.buttonHeaderSubject.Width > listView1.MaximumSize.Height * 0.65)
                obj.buttonHeaderSubject.Width = (int)(listView1.MaximumSize.Height * 0.65);
            obj.columnSubject.Width = buttonHeaderSubject.Width - 1;
            obj.buttonHeaderDate.Left = buttonHeaderSubject.Left + buttonHeaderSubject.Width;
            if (obj.buttonHeaderDate.Width > listView1.MaximumSize.Height * 0.5)
                obj.buttonHeaderDate.Width = (int)(listView1.MaximumSize.Height * 0.5);
            obj.columnDate.Width = buttonHeaderDate.Width - 26;
            obj.listView1.Width = listView1.Width = columnID.Width + columnFrom.Width + columnSubject.Width + columnDate.Width + 25;
            //
            obj.zbutlist.Width = listView1.Width + 2;
            obj.Width = listView1.Width + 48;
            obj.zbutpanel.Width = Width;
            obj.textBoxSearch.Left =listView1.Width - 169; // 392
            obj.labelSearch.Left = listView1.Width - 217;//  344
            obj.labelStop.Left = listView1.Width - 55;// 506
            obj.labelMenu.Left = listView1.Width - 55; // 506
            
        }
        // изменение высоты окна
        public void HeightSizeChange()
        {
            if (Parent!=null)
                Height = Parent.Height - 66;
            zbutpanel.Height = Height;
            this.textBoxSearch.Top = Height - 17 - 21;
            this.labelSearch.Top = Height - 17 - 18;
            this.labelStop.Top = Height - 17;
            this.labelMenu.Top = Height - 17 - 18; // 341
            this.labelShowCount.Top = Height - 17 - 18;
            this.labelAll.Top = Height - 17;
            listView1.Height = Height - 78;
            zbutlist.Height = Height - 76;
        }
        #endregion      
        

        // принимается ли почта
        bool receiving = false;
        pop3 pop;
        int numberReceived = 0;

        /// <summary>
        ///             ОСНОВНАЯ функция - соединение.
        /// </summary>
        public void ReceiveMail()
        {
            if (receiving)
                return;
            pop_ResponceAdded("Подключение");
            // если не принимается...
            pop = new pop3(mServer,mPort,mSsl);
            pop.ResponceAdded += new dResp(pop_ResponceAdded);
            //
            try
            {
                // установили соединение
                if (pop.SetConnect(mLogin, mPassword))
                {
                    receiving = true;
                    pop_LabelStopMessage("остановить...");
                }
                else
                    return;
                numberReceived = 0;
                // надо найти стартовое сообщение - с чего начинать...
                int startMessage = pop.StartMessageRecognition(Application.UserAppDataPath + "\\" + mMailName + "\\_+log.xml");
                //
                // теперь
                for (int i = startMessage; i <= pop.MyPostBox.NumberOfMessages; i++)
                {
                    if (receiving)   // может быть остановлено во время выполнения.
                    {
                        Message mess = pop.ReceiveMessage(i);
                        if (mess != null)
                        {
                            numberReceived++;
                            SaveMessage(mess);
                        }
                        else if (mess == null) // если остановлено
                        {
                            pop_LabelStopMessage("проверить ящик");
                            pop.EndConnect();
                        }
                    }
                    else if (!receiving)
                    {
                        pop_ResponceAdded("Остановлено. " + numberReceived + " cообщений принято.");
                        pop_LabelStopMessage("проверить ящик");
                        break;
                    }
                }
                if (!pop.MyPostBox.StoppedFromAnOtherProcess && receiving) // если успешно закончено
                {
                    receiving = false;
                    pop_ResponceAdded(numberReceived + " cообщений принято.");
                }
                pop_LabelStopMessage("проверить ящик");
                pop.EndConnect();
            }
            catch (Exception exc)
            {
                pop_ResponceAdded("Ошибка: (ReceiveMail) " + exc.Message.ToString());
                pop_LabelStopMessage("проверить ящик");
                pop.EndConnect();
            }
            
        }
        
        // Остановка соединения...Или наоборот запуск нового потока для проверки ящика. Вот.
        void labelStop_Click(object sender, EventArgs e)
        {
            if (labelStop.Text == "проверить ящик")
            {
                try
                {
                    labelStop.Text = "остановить...";
                    Thread kk = new Thread(ReceiveMail);
                    kk.Start();
                }
                catch (Exception exc)
                {
                    pop_ResponceAdded("Ошибка: labelStop (Start Thread)" + exc.Message.ToString());
                }
            }
            else if (labelStop.Text == "остановить...")
            {
                try
                {
                    if (receiving)
                    {
                        receiving = false;
                        pop.MyPostBox.StoppedFromAnOtherProcess = true;
                    }
                }
                catch (Exception exc)
                {
                    pop_ResponceAdded("Ошибка: labelStop (EndConnection)" + exc.Message.ToString());
                }
            }
        }

        /// <summary>
        /// Изменение "статусной" строки...
        /// </summary>
        void pop_ResponceAdded(string str)
        {
            if (labelAll.InvokeRequired)
            {
                dResp d = new dResp(pop_ResponceAdded);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                labelAll.Text = str;
            }
            
        }
        
        /// <summary>
        /// Изменение надписи остановить/проверить
        /// </summary>
        void pop_LabelStopMessage(string str)
        {
            if (labelAll.InvokeRequired)
            {
                dResp d = new dResp(pop_LabelStopMessage);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                labelStop.Text = str;
            }

        }
        
        /// <summary>
        /// Сохранение сообщения. Вызывается из ReceiveMail()
        /// </summary>
        private void SaveMessage(Message _message)
        {
            ListViewSE messType = ListViewSE.InBox;
            if (listView1.InvokeRequired)
            {
                dTable d = new dTable(SaveMessage);
                this.Invoke(d, new object[] { _message });
            }
            else
            {
                try
                {
                    if (_message.receivedfrom == "")
                    {
                        messType = ListViewSE.OutBox;
                        if (_message.to.Contains(mMailName) && !_message.from.Contains(mMailName))
                            messType = ListViewSE.InBox;
                    }
                    else
                        messType = ListViewSE.InBox;
                    //
                    XDocument XDoc = new XDocument(
                        new XDeclaration("1.0", "utf-8", "yes"),
                        new XComment("Last edition:" + DateTime.Now.ToString()),
                        new XElement("MailList")
                        );
                    XElement mh =
                        new XElement("Mail"+messType,
                            new XElement("From", _message.from),
                            new XElement("To", _message.to),
                            new XElement("Subject", _message.subject),
                            new XElement("Date", _message.date),
                            new XElement("Size", _message.size)
                        );
                    XDoc.Root.Add(mh);
                    Directory.CreateDirectory(Application.UserAppDataPath + "\\" + mMailName);
                    XDoc.Save(Application.UserAppDataPath + "\\" + mMailName + "\\"+_message.uidl+".xml");
                }
                catch (Exception exc)
                {
                    pop_ResponceAdded("Ошибка: SaveMessage(in File): " + exc.Message.ToString());
                }
                // добавим в файл - логлист - свой для каждого ящика
                AddToLogList(_message.number.ToString(), _message.from, _message.to,
                    _message.subject, _message.date, _message.uidl, _message.size, messType
                    );
                // а это в listview.
                if (textBoxSearch.Text=="")
                    AddToListView(_message.number.ToString(), _message.from, _message.to,
                        _message.subject, _message.date, _message.uidl, messType
                        );
            }
        }
        
        /// <summary>
        ///  Добавление информации в сам ListView. Поле с именем файла скрыто
        /// </summary>
        public void AddToListView(string _numb, string messFrom, string messTo,
            string messSubj, string messDate, string messUIDL, ListViewSE type)
        {
            try
            {
                if (type == showingListView)
                {
                    ListViewItem lvItem = listView1.Items.Add((listView1.Items.Count + 1).ToString());
                    if (type==ListViewSE.InBox)
                        lvItem.SubItems.Add(messFrom);
                    if (type == ListViewSE.OutBox)
                        lvItem.SubItems.Add(messTo);
                    lvItem.SubItems.Add(messSubj);
                    lvItem.SubItems.Add(messUIDL);
                    lvItem.SubItems.Add(messDate);
                    SetShowLabel(listView1.Items.Count,listView1.Items.Count,type);
                }
            }
            catch (Exception exc)
            {
                pop_ResponceAdded("Ошибка: AddToList: " + exc.Message.ToString());
            }
        }
        
        /// <summary>
        ///  Есть общий лог лист файл, в котором храняться данные о всех сообщениях в ящике
        ///  В том числе удаленных (без имени файла и с пометкой deleted);
        /// </summary>
        public void AddToLogList(string _numb, string messFrom,string messTo, 
            string messSubj, string messDate, string messUIDL, int messSize, ListViewSE type)
        {
            try
            {
                string messLogFile = Application.UserAppDataPath + "\\" + mMailName + "\\_+log.xml";
                XDocument XDoc;
                if (!File.Exists(messLogFile))
                {
                    XDoc = new XDocument(
                            new XDeclaration("1.0", "utf-8", "yes"),
                            new XComment("Last edition:" + DateTime.Now.ToString()),
                            new XElement("MailList")
                            );
                }
                else
                {
                    XDoc = XDocument.Load(messLogFile);
                }
                XElement set =
                    new XElement("Mail"+type.ToString(),
                        new XAttribute("id", _numb),
                        new XAttribute("Date", messDate),
                        new XAttribute("Size", messSize.ToString()),
                        new XAttribute("Deleted", false),  // новое сообщение всегда существует
                        new XElement("From", messFrom),
                        new XElement("To", messTo),
                        new XElement("Subject", messSubj),
                        new XElement("UIDL", messUIDL) // filename - это всегда uidl
                    );
                XDoc.Root.Add(set);
                Directory.CreateDirectory(Application.UserAppDataPath + "\\" + mMailName);
                XDoc.Save(messLogFile);
            }
            catch (Exception exc)
            {
                pop_ResponceAdded("Ошибка: AddToLogList: " + exc.Message.ToString());
            }
        }
        //
        private void SetShowLabel(int all, int show, ListViewSE type)
        {
            if (type == ListViewSE.InBox)
                labelShowCount.Text = "Входящие. Всего: " + all + ". Показано: " + show;
            if (type == ListViewSE.OutBox)
                labelShowCount.Text = "Отправленные. Всего: " + all + ". Показано: " + show;
        }

        void buttonOutBox_Click(object sender, EventArgs e)
        {
            showingListView = ListViewSE.OutBox;
            buttonOutBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(50)))), ((int)(((byte)(90)))));
            buttonInBox.BackColor = Color.Black;
            
            LoadMessageFromFile("");
        }

        void buttonInBox_Click(object sender, EventArgs e)
        {
            showingListView = ListViewSE.InBox;
            buttonInBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(50)))), ((int)(((byte)(90)))));
            buttonOutBox.BackColor = Color.Black;
            LoadMessageFromFile("");
        }

        public void LoadMessageFromFile(string searchCond)
        {
            if (listView1.InvokeRequired)
            {
                dResp d = new dResp(LoadMessageFromFile);
                this.Invoke(d, new object[] { searchCond });
            }
            else
            {
                listView1.Items.Clear();
                SetShowLabel(0, 0, showingListView);
                if (!Directory.Exists(Application.UserAppDataPath + "\\" + mMailName))
                    return;
                if (!File.Exists(Application.UserAppDataPath + "\\" + mMailName + "\\_+log.xml"))
                    return;
                XDocument XDoc = XDocument.Load(Application.UserAppDataPath + "\\" + mMailName + "\\_+log.xml");
                int all = 0;
                int founded = 0;
                foreach (XElement mlh in XDoc.Element("MailList").Elements())
                {
                    if (mlh.Name == "Mail" + ShowingListView.ToString())
                    {
                        string fr = "", to = "";
                        if (showingListView == ListViewSE.InBox)
                            fr = (string)mlh.Element("From");
                        else
                            to = (string)mlh.Element("To");
                        string dt = (string)mlh.Attribute("Date");
                        string sb = (string)mlh.Element("Subject");
                        string ud = (string)mlh.Element("UIDL");
                        all++;
                        if (searchCond == "")
                        {
                            founded++;
                            AddToListView(founded.ToString(), fr, to, sb, dt, ud, showingListView);
                        }
                        else if (searchCond != "")
                        {
                            if (fr.ToLower().Contains(searchCond.ToLower()) || 
                                to.ToLower().Contains(searchCond.ToLower()) ||
                                sb.ToLower().Contains(searchCond.ToLower()) ||
                                dt.ToLower().Contains(searchCond.ToLower()))
                            {
                                founded++;
                                AddToListView(founded.ToString(), fr, to, sb, dt, ud, showingListView);
                            }
                        }
                        SetShowLabel(all, founded, showingListView);
                    }
                }
                SetShowLabel(all, founded, showingListView);
            }
        }
        private void textBoxSearch_KeyUp(object sender, KeyEventArgs e)
        {
            LoadMessageFromFile(textBoxSearch.Text);
        }
    }
}
